<template>
  <div class="">
    <el-dialog title="请使用移动管理端扫码" :show-close="false" @close="closeDialog" @open="openDialog"
      :visible.sync="dialogVisible" width="30%" :before-close="handleClose">
      <el-link type="warning" @click="loadCode">刷新二维码</el-link>
      <el-image style="width: 100%; height: 100%" :src="qrCode"></el-image>
    </el-dialog>
  </div>
</template>

<script>
import { getLoginStatus, getLoginQRCode } from '@/api/login/qrCodeLogin'

export default {
  name: 'LoginQRCode',
  props: {
    dialogVisible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      qrCode: '',
      //0 未扫码 1 已认证 2 已过期
      qrCodeStatus: null,
      // 二维码token
      qrCodeToken: '',
      interval: null,
      // 登录成功后，返回的accessToken
      accessToken: '',
      isRefreshing: false, // 防止快速点击刷新
      refreshCoolDown: 2000 // 刷新冷却时间（毫秒）
    }
  },
  methods: {
    async openDialog() {

      this.loadCode()
    },
    closeDialog() {
      this.stopPolling()
      this.$emit('handle-close')
    },
    async loadCode() {
      if (this.isRefreshing) {
        console.log('正在刷新二维码，请稍后...');
        return // 如果正在刷新，直接返回
      }

      this.isRefreshing = true;
      try {
        this.stopPolling()
        this.qrCodeToken = ''
        let res = await getLoginQRCode()

        this.qrCode = res.codeBase64
        this.qrCodeToken = res.qrCodeToken
        this.startPolling()
      } catch (e) {

        console.error('加载二维码失败:', error);
        this.$message.error('加载二维码失败，请稍后再试');
      } finally {
        // 设置冷却时间后，将isRefreshing设置为false
        setTimeout(() => {
          this.isRefreshing = false;
        }, this.refreshCoolDown);
      }
    },
    startPolling() {
      this.qrCodeStatus = 0
      //开启轮询查询登录状态
      this.interval = setInterval(() => {
        this.polling()
      }, 500)

    },
    stopPolling() {
      //关闭轮询查询登录状态
      clearInterval(this.interval)
    },
    async polling() {
      try {
        const res = await getLoginStatus(this.qrCodeToken);
        this.qrCodeStatus = res.qrCodeStatus;

        if (this.qrCodeStatus == 2) {
          this.stopPolling();
          this.$message.warning('长时间无人响应，二维码已过期');
        }

        if (res.accessToken) {
          this.accessToken = res.accessToken;
          this.qrCodeToken = '';
          this.qrCodeStatus = 1;
          this.stopPolling();
          this.$emit('handle-success', this.accessToken);
        }
      } catch (error) {
        console.error('轮询状态失败:', error);
        this.$message.error('轮询状态失败，请稍后再试');
        this.stopPolling();
      }
    }
    ,
    handleClose() {
      this.stopPolling()
      this.$emit('handle-close')
    }
  },
  created() {

  },
  mounted() {

  },
}
</script>

<style scoped></style>
